#include "iapminimal.h"
#include <QStringBuilder>
#include <QTimer>
#include <QDateTime>


#define PRODUCTID "751224"

IAPminimal::IAPminimal(QObject *parent) :
    QObject(parent),
    isbusy(false)
{
    qRegisterMetaType<IAPClient::ProductDataHash>("IAPClient::ProductDataHash");
    startIAP();
}

IAPminimal::~IAPminimal()
{
    stopIAP();
}

void IAPminimal::getProductData()
{
    if(isbusy)
        return;

    startIAP();
    iap_client->getProductData(PRODUCTID);
    emit statusBusy();
    isbusy = true;
}

void IAPminimal::purchaseProduct()
{
    if(isbusy)
        return;

    startIAP();
    iap_client->purchaseProduct(PRODUCTID, IAPClient::ForcedAutomaticRestoration);
    emit statusBusy();
    isbusy = true;
}

void IAPminimal::productDataReceived(int /*requestId*/, QString status, IAPClient::ProductDataHash productData)
{
    isbusy = false;

    QString result = status;

    if(QString::compare(status, "OK", Qt::CaseInsensitive)==0){
        result = "id : " % productData.value("id").toString() % "\n" %
                "info : " % productData.value("info").toString() % "\n" %
                "shortdescription : " % productData.value("shortdescription").toString() % "\n" %
                "price : " % productData.value("price").toString() %
                "\n Clickme to buy this product";
    }

    emit productDataComplete(result);
}

void IAPminimal::closeIAP()
{
    stopIAP();
    QTimer::singleShot(21000, this, SIGNAL(iapClosed()));
    emit statusBusy();
    isbusy = true;
}

void IAPminimal::stopIAP()
{
    delete iap_client;
    iap_client = NULL;
}

void IAPminimal::startIAP()
{
    if(iap_client)
        return;

    // NOTE: this is syncronous operation takes considerable amount of time
    iap_client = new IAPClient();
    connect(iap_client, SIGNAL(productDataReceived( int, QString, IAPClient::ProductDataHash)), this,
            SLOT(productDataReceived(int, QString, IAPClient::ProductDataHash)), Qt::QueuedConnection);
    connect(iap_client, SIGNAL(purchaseCompleted( int , QString, QString)), this,
            SLOT(purchaseCompleted( int , QString, QString)),Qt::QueuedConnection);
    connect(iap_client, SIGNAL(purchaseFlowFinished(int)), this, SLOT(purchaseFlowFinished(int)), Qt::QueuedConnection);
}

void IAPminimal::purchaseFlowFinished( int /*requestId*/ )
{
    isbusy = false;
}

void IAPminimal::purchaseCompleted( int /*requestId*/, QString status, QString purchaseTicket )
{

    QString result = "purchaseCompleted : " % status % "\nclickme to exit the app";

    emit productPurchaseComplete(result);
}

